/* eslint-disable babel/camelcase */
/**
 * 订单核心数据概览
 * @author hanzhichen (hanzhichen@baijia.com)
 * @date 2021-03-02
 */

import {useState, useCallback, useEffect, useMemo} from 'react';
import {useRequest} from 'ahooks';
import {Card, message} from 'antd';
import {querySelectOptions, queryValues} from '~/service/refundReport';
import {INPUT_TYPE_ENUM} from '~/component/SearchForm/dateRanges';
import {lineOptions as produceOptions} from '~/utils/common/reportEcharts';
import {fetchReports, getReportInfo} from '~/service/reports';
import SearchForm from '../../common/CommonSearchBar';
import {
    convertSearcherParams,
    formatRangePickerValue,
    getQueryParams
} from '../../common/utils';
import {groupByData, getFormatter} from '../utils/indicator';
import RealTimeStatisticsView from './RealtimeStatisticsView';
import {searchFormCfg, selectUnitId} from './config';

// 设置默认时间
const initValues = {};
const formItemLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16}
};
const tailLayout = {
    wrapperCol: {span: 24}
};
const formatDateSearchValueToDate = formatRangePickerValue('YYYYMMDD');
const formatDateSearchValueToTime = formatRangePickerValue('YYYY-MM-DD HH:mm');
const getToolTipPosition = (point, params, dom, rect, size) => {
    let [left, top] = point || [];
    const {contentSize = [], viewSize = []} = size || {};
    const [contentWidth, contentHeight] = contentSize;
    const [viewWidth, viewHeight] = viewSize;
    const minLeft = 0;
    const minTop = 0;
    const maxLeft = viewWidth - contentWidth;
    const maxTop = viewHeight - contentHeight;
    if (top > maxTop) {
        top = maxTop;
    }
    if (left > maxLeft) {
        left = maxLeft;
    }
    if (top < minTop) {
        top = minTop;
    }
    if (left < minLeft) {
        left = minLeft;
    }
    return [left, top];
};

// 将searchForm返回的值转化为后端需要的格式
const convertParams = params => {
    // 转换参数
    const {originPaidDay, ...rest} = params || {};
    let newSearcherParams = params;
    if (originPaidDay == null) {
        newSearcherParams = rest;
    } else {
        const formattedPayDate = formatDateSearchValueToDate(originPaidDay);
        const formattedPayTime = formatDateSearchValueToTime(originPaidDay);
        newSearcherParams = {
            dt: formattedPayDate,
            // eslint-disable-next-line babel/camelcase
            paid_time: formattedPayTime,
            ...rest
        };
    }
    const queryParams = convertSearcherParams(newSearcherParams);
    return queryParams;
};

/** 把searchFormValue转换成查询接口参数的permissions */
const convertParamsToPermissions = (params, reportDimension, searchFormCfg) => {
    const paramList = convertSearcherParams(params);
    // 添加label
    paramList.forEach(item => {
        const cfg = searchFormCfg.find(item1 => item1.key === item.dimensionId);
        item.beDimensionName = cfg.dimensionName;
    });
    const permissions =
        paramList?.map(aParam => {
            const rdItem =
                reportDimension?.find(
                    ele => ele.dimensionName === aParam.beDimensionName
                ) ?? {};
            const dimensionId = rdItem?.dimensionId;
            if (aParam?.dimensionId === 'begin_date') {
                const filterItems = Array.isArray(aParam?.value)
                    ? aParam?.value.map(vItem => vItem.format('YYYYMMDD'))
                    : [];
                return {
                    dimensionId,
                    filterItems
                };
            }
            return {
                dimensionId,
                filterItems: Array.isArray(aParam?.value)
                    ? aParam.value
                    : aParam.value == null
                        ? []
                        : [aParam.value]
            };
        }) ?? [];
    return permissions;
};

/**
 * 专题课行课数据第二张报表 的 Part1
 * 这部分包括筛选器, 折线图, 表格.
 * 接口方面, 筛选器selectOptions接口是/api/agility/view/xxx;
 * 折线图和表格的数据接口是/api/portal/search:
 * 参数为{"id":398,"permissions":[{"dimensionId":"4593","filterItems":["20210302"]}]}
 * 准备在查询时再转换参数.
 */
const Part1 = props => {
    // 分别对应图和表格
    const {id1: chartId} = props;
    // 查询模块数据时, 不同模块数据使用相同的筛选器, 但后端实际的dimensionId不同, 需要动态匹配.
    const [chartReportDimension, setChartReportDimension] = useState([]);
    const [tableReportDimension, setTableReportDimension] = useState([]);

    useEffect(() => {
        // query chartId dimemsions
        chartId &&
            getReportInfo({id: chartId})
                .then(res => {
                    const reportDimension = res?.data?.reportDimension ?? [];
                    setChartReportDimension(reportDimension);
                })
                .catch(error => {
                    if (error) {
                        console.log(error, 'error');
                    }
                });
    }, [chartId]);
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState({});
    // 对比弹框表单值缓存
    const [compareSearchFormValues, setCompareSearchFormValues] = useState({});

    // 查询参数, 缓存起来给下载用?
    const [chartQueryParams, setChartQueryParams] = useState({});
    // 查询参数, 缓存起来给下载用?
    const [tableQueryParams, setTableQueryParams] = useState({});

    // chart查询方法
    const {
        data: chartData,
        loading: chartLoading,
        run: queryChart,
        mutate: setChartData
    } = useRequest(fetchReports, {
        manual: true,
        formatResult(res) {
            return res?.data ?? {};
        }
    });
    // 添加chart比较查询方法
    const {
        data: compareChartData,
        loading: compareChartLoading,
        run: queryCompareChart,
        mutate: setCompareChartData
    } = useRequest(fetchReports, {
        manual: true,
        formatResult(res) {
            return res?.data ?? {};
        }
    });

    const [newXValue, setNewXValue] = useState();
    const [isToAdd, setIsToAdd] = useState(false);
    const [hasAdded, setHasAdded] = useState(false);
    // const [canUpdateChart, setCanUpdateChart] = useState(true);
    const [chartOptions, setChartOptions] = useState({});
    const [searchLessonsNum, setSearchLessonsNum] = useState(1);
    const [addSearchLessonsNum, setAddSearchLessonsNum] = useState(1);

    // 用于产生Echarts的配置和合并Echarts的配置
    const getDataMap = (newChartData = {}, isToAdd) => {
        const period = INPUT_TYPE_ENUM.SINGLE_DAY;

        const {dataSource = [], columns = []} = newChartData || {};

        const newDateDim =
            columns?.find(item => item?.title === '日期')?.key ?? '';

        let data = [];
        for (const item of columns) {
            if (item.key.indexOf('field') !== -1) {
                data = data?.concat(
                    groupByData(dataSource, newDateDim, item.key, item.title)
                );
            }
        }
        const newOptions = produceOptions(data, period);
        if (isToAdd) {
            newOptions.legend.data = chartOptions.legend.data
                .slice(0, searchLessonsNum)
                .concat(newOptions.legend.data);
            newOptions.series = chartOptions.series
                .slice(0, searchLessonsNum)
                .concat(newOptions.series);
            const newXvalue = newOptions.xAxis.data;
            newOptions.xAxis = chartOptions.xAxis;
            newOptions.tooltip.formatter = getFormatter(
                newXvalue,
                newOptions,
                searchLessonsNum
            );
            setNewXValue(newXvalue);
            setHasAdded(true);
        }
        if (!isToAdd && hasAdded) {
            newOptions.legend.data = newOptions.legend.data.concat(
                chartOptions.legend.data.slice(-addSearchLessonsNum)
            );
            newOptions.series = newOptions.series.concat(
                chartOptions.series.slice(-addSearchLessonsNum)
            );
            newOptions.tooltip.formatter = getFormatter(
                newXValue,
                newOptions,
                searchLessonsNum
            );
        }
        // 是否默认选中
        const select = {};
        for (const item of newOptions.legend.data) {
            select[item] = false;
            // TODO: 修改成 在线人数
            if (item.indexOf('在线人数') !== -1) {
                select[item] = true;
            }
        }
        newOptions.legend.selected = select;

        // Y轴间距只能是正整数
        newOptions.yAxis.minInterval = 1;
        // 添加底部拖动
        newOptions.dataZoom = [
            {
                type: 'slider',
                show: true,
                realtime: true,
                start: 0,
                end: 100
            }
        ];
        newOptions.tooltip.position = getToolTipPosition;
        // setChartOptions(newOptions);
        return newOptions;
    };

    // 查询完, 设置echartOptions.
    useEffect(() => {
        const newChartData = isToAdd ? compareChartData : chartData;
        const newChartDataSource = newChartData?.dataSource ?? [];
        if (isToAdd && newChartDataSource.length === 0) {
            message.warning('该对比课节没数哦，请重新选择');
            return;
        }
        const newChartOptions = getDataMap(newChartData, isToAdd);
        setChartOptions(newChartOptions);
    }, [chartData, compareChartData, isToAdd]);

    /** 点击搜索按钮 */
    const handleSearch = formValues => {
        // 缓存当前表单数据
        setSearchFormValues(formValues);
        // 获取查询参数
        const chartPermissions = convertParamsToPermissions(
            formValues,
            chartReportDimension,
            searchFormCfg
        );
        // 缓存一个啥玩意
        const length = chartPermissions.reduce((res, item) => {
            const itemLengt = item.filterItems.length;
            return itemLengt > res ? itemLengt : res;
        }, 1);
        setSearchLessonsNum(length * 3);
        setAddSearchLessonsNum(3);
        // 构建查询参数
        const chartQueryParams = getQueryParams(chartId, chartPermissions);
        // 缓存查询参数
        setChartQueryParams(chartQueryParams);
        // 重新设置
        setIsToAdd(false);
        // 查询
        queryChart(chartQueryParams);
    };

    /** 点击重置按钮 */
    const handleReset = () => {
        // 缓存当前表单数据
        setSearchFormValues(initValues);
        // 缓存legend长度?
        setSearchLessonsNum(3);
        setAddSearchLessonsNum(3);
        // 重新设置
        setIsToAdd(false);
        // 重置图表数据
        setChartData({});
        // 重置已添加对比
        setHasAdded(false);
    };

    // 请求单个表单配置项
    const handleFetchOptions = ({
        key,
        searchKey,
        pager,
        dependItemKey,
        dependItemValue,
        isGetingMore,
        options: curOptions,
        fieldsValue
    }) => {
        const permissions = searchFormCfg
            ?.map(item => {
                if (item.key === 'begin_date') {
                    const filterItems = fieldsValue[item.key]
                        ? [fieldsValue[item.key]?.format('YYYYMMDD'), fieldsValue[item.key]?.format('YYYYMMDD')]
                        : [];
                    return {
                        dimensionId: `${selectUnitId}_${item.key}`,
                        dimensionName: item.key,
                        filterItems
                    };
                }
                return {
                    dimensionId: `${selectUnitId}_${item.key}`,
                    dimensionName: item.key,
                    filterItems: Array.isArray(fieldsValue[item.key])
                        ? fieldsValue[item.key]
                        : fieldsValue[item.key] == null
                            ? []
                            : [fieldsValue[item.key]]
                };
            })
            ?.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: `${selectUnitId}_${key}`,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: selectUnitId
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    /** 点击添加对比 */
    const handleAddOk = formValues => {
        // 不缓存当前表单数据
        // setSearchFormValues(formValues);
        // 获取查询参数
        const chartPermissions = convertParamsToPermissions(
            formValues,
            chartReportDimension,
            searchFormCfg
        );
        // 缓存另一个维度
        const length = chartPermissions.reduce((res, item) => {
            const itemLengt = item.filterItems.length;
            return itemLengt > res ? itemLengt : res;
        }, 1);
        setAddSearchLessonsNum(length * 3);

        // 构建查询参数
        const comPareChartQueryParams = getQueryParams(chartId, chartPermissions);
        // 缓存查询参数
        setCompareSearchFormValues(comPareChartQueryParams);
        setIsToAdd(false);
        // 查询
        queryCompareChart(comPareChartQueryParams).then(() => {
            setIsToAdd(true);
        });
    };

    /** 点击清除 */
    const handleClear = data => {
        // 缓存当前表单数据
        setSearchFormValues(initValues);
        // 重置图表数据
        if (newXValue) {
            const options = chartOptions;
            options.legend.data = options.legend.data.slice(0, searchLessonsNum);
            options.series = options.series.slice(0, searchLessonsNum);
            options.tooltip.formatter = null;
            // 是否默认选中
            const select = {};
            for (const item of options.legend.data) {
                select[item] = false;
                if (item.indexOf('在线人数') !== -1) {
                    select[item] = true;
                }
            }
            options.legend.selected = select;

            setChartOptions(options);
            setNewXValue(null);
            setHasAdded(false);
            setAddSearchLessonsNum(0);
        } else {
            message.warning('还未添加对比数据');
        }
    };

    return (
        <Card
            className="special-class-order-offline"
            title="直播间实时到客数据"
        >
            <SearchForm
                noCache
                formItemLayout={formItemLayout}
                tailLayout={tailLayout}
                labelAlign="left"
                config={searchFormCfg}
                selectOptions={selectOptions}
                initialValues={initValues}
                onOk={handleSearch}
                onReset={handleReset}
                onfetchOptions={handleFetchOptions}
                loading={chartLoading || compareChartLoading}
            />
            {/* <Card> */}
            {chartId && (
                <RealTimeStatisticsView
                    id={chartId}
                    isloading={chartLoading}
                    canClear={hasAdded}
                    queryParams={chartQueryParams}
                    dataSource={chartData?.dataSource ?? []}
                    dataMapOptions={chartOptions}
                    onOk={handleAddOk}
                    onClear={handleClear}
                />
            )}
            {/* </Card> */}
        </Card>
    );
};

export default Part1;
